<?php
require_once 'DB.class.php';
class City
{
    private $_id;
    private $_name;
    private $_longitude;
    private $_latitude;


    public static function findByName($name)
    {
        $db = DB::getInstance();
        $sql = "select id, name, longitude, latitude from city where lower(name)=lower(:name) and longitude is not null and latitude is not null";
        $stmt = $db->prepare($sql);
        if (!$stmt instanceof PDOStatement) {
            throw new Excepton("Cannot prepare the query");
        }
        if (!$stmt->execute(array(':name' => strtolower($name)))) {
            throw new Exception("Cannot execute the query: " . print_r($stmt->errorInfo(), true));
        }
        return self::createFromArray($stmt->fetch());
    }

    private static function createFromArray($data)
    {
        $city = new City();
        $city->setId($data['id']);
        $city->setName($data['name']);
        $city->setLongitude($data['longitude']);
        $city->setLatitude($data['latitude']);
        return $city;
    }

    public static function getCities()
    {
        $db = DB::getInstance();
        $sql = "select distinct city.id, city.name, city.longitude, city.latitude from city left join business on city.id=city_id where business.longitude is not null and business.latitude is not null order by city.name";
        $stmt = $db->prepare($sql);
        if (!$stmt instanceof PDOStatement) {
            throw new Excepton("Cannot prepare the query");
        }

        if (!$stmt->execute()) {
            throw new Exception("Cannot execute the query: " . print_r($stmt->errorInfo(), true));
        }
        $cities = array();
        while ($row = $stmt->fetch())
        {
            $city = self::createFromArray($row);
            $cities[] = $city;
        }
        return $cities;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getId()
    {
        return $this->_id;
    }

    public function setName($name)
    {
        $this->_name = $name;
    }

    public function setId($id)
    {
        $this->_id = $id;
    }


    public function setLongitude($longitude)
    {
        $this->_longitude = $longitude;
    }

    public function setLatitude($latitude)
    {
        $this->_latitude = $latitude;
    }

    public function getLongitude()
    {
        return $this->_longitude;
    }

    public function getLatitude()
    {
        return $this->_latitude;
    }


}
